package com.yao;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

/**
 * 权限拦截器
 */
@Aspect
@Component
public class AuthorizationAspect {

    public static final Logger logger = Logger.getLogger(AuthorizationAspect.class);

    @Value("${spring.profiles}")
    private String env;

    /**
     * 定义切点
     */
    @Pointcut("execution(* com.yao.service..*(..))")
    public void servicePointCut(){

    }

    /**
     * 实现拦截器
     * @param joinPoint
     * @return
     */
    @Around("servicePointCut()")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod(); //获取被拦截的方法
        String methodName = method.getName(); //获取被拦截的方法名
        Set<Object> allParams = new LinkedHashSet<>(); //保存所有请求参数，用于输出到日志中
        logger.info("方法开始前的操作");
        logger.info("请求开始，方法："+methodName);
        Object proceed = joinPoint.proceed();
        return proceed;


        /*Object result = null;

        Object[] args = joinPoint.getArgs();

        for(Object arg : args){
            //logger.debug("arg: {}", arg);
            if (arg instanceof Map<?, ?>) {
                //提取方法中的MAP参数，用于记录进日志中
                @SuppressWarnings("unchecked")
                Map<String, Object> map = (Map<String, Object>) arg;

                allParams.add(map);
            }else if(arg instanceof HttpServletRequest){
                HttpServletRequest request = (HttpServletRequest) arg;
                if(isLoginRequired(method)){
                    if(!isLogin(request)){
                        result = new JsonResult(ResultCode.NOT_LOGIN, "该操作需要登录！去登录吗？\n\n（不知道登录账号？请联系老许。）", null);
                    }
                }

                //获取query string 或 posted form data参数
                Map<String, String[]> paramMap = request.getParameterMap();
                if(paramMap!=null && paramMap.size()>0){
                    allParams.add(paramMap);
                }
            }else if(arg instanceof HttpServletResponse){
                //do nothing...
            }else{
                //allParams.add(arg);
            }
        }*/
    }

    /**
     * 判断一个方法是否需要登录
     * @param method
     * @return
     */
   /* private boolean isLoginRequired(Method method){
        if(!env.equals("prod")){ //只有生产环境才需要登录
            return false;
        }

        boolean result = true;
        if(method.isAnnotationPresent(Permission.class)){
            result = method.getAnnotation(Permission.class).loginReqired();
        }

        return result;
    }*/
}
